<script setup>
import {ref } from 'vue'
import router from '../config/router';
const searchTag = ref('')
// 搜索方法
const onSearch = () => {
    //  根据搜索的关键字匹配选项 每次搜索就能出来一个对应的标签
    items.value = originTagList.map(parentTag => {
        const tempChildrenTag = [...parentTag.children]
        const tempParentTag = { ...parentTag }
        tempParentTag.children = tempChildrenTag.filter(childrenTag => childrenTag.text.includes(searchTag.value))
        return tempParentTag;
    })
    // 删除多余的部分 直接显示搜索的标签选项
    items.value = items.value.filter(parentTag => {
        if (parentTag.children.length !== 0) {
            return parentTag;
        }
    })
}

// 取消搜索方法
const onCancel = () => {
    searchTag.value = '';
    items.value = originTagList;

}

const activeIds = ref([]);  // item 的id
const activeIndex = ref(0);  // 导航的id
const originTagList = [
    {
        text: '方向',
        children: [
            { text: 'java', id: 'java' },
            { text: 'c++', id: 'c++' },
            { text: 'python', id: 'python' },
        ],
    },
    {
        text: '目前状态',
        children: [
            { text: '大一', id: '大一' },
            { text: '大二', id: '大二' },
            { text: '大三', id: '大三' },
            { text: '研一', id: '研一' },
            { text: '研二', id: '研二' },
            { text: '研三', id: '研三' }
        ],
    }
];

let items = ref([...originTagList]);

const click_item = () => {
    console.log(activeIds.value);
}
const deleteActiveIds = (index) => {
    activeIds.value.splice(index, 1);
}
const doSearchResult = () => {
    router.push({
        path: '/list',
        query: {
           tags: activeIds.value
        }
    })
}

</script>
<!-- template 元素 -->
<template>
    <div id="search">
        <form action="/">
            <van-search v-model="searchTag" placeholder="请输入标签名称" show-action @search="onSearch" @cancel="onCancel" />
        </form>

        <van-divider>已选标签</van-divider>
        <div style="margin: 10px 0;">
            <!-- <van-row gutter="20">
                    <van-rol span="10" offset="4"> {{ item }}</van-rol>
                </van-row> -->
            <van-row gutter="20px" :wrap=true>
                <div v-if="activeIds !== null" v-for="(item, index) in activeIds" :key="item">
                    <van-tag :show="true" closeable size="large" type="primary" @close="deleteActiveIds(index)"
                        style="margin: 5px 10px;">
                        {{ item }}
                    </van-tag>
                </div>
            </van-row>
        </div>
        <van-divider>推荐标签</van-divider>
        <div id="all-tags">
            <van-tree-select v-model:active-id="activeIds" v-model:main-active-index="activeIndex" :items="items"
                @click-item=click_item />
        </div>

        <div style="padding: 0 10px;">
            <van-button block type="primary" @click="doSearchResult()">筛选</van-button>
        </div>


    </div>
</template>

<style scoped></style>